/**
 * [1002] 查找共用字符
 *
 * @format
 * @lc app=leetcode.cn id=1002 lang=javascript
 */

// @lc code=start
/**
 * @param {string[]} words
 * @return {string[]}
 */
var commonChars = function (words) {
    // 两个字符串求交集，但不能用 Set 因为同一字符串中出现两次的相同字符是两个不同的元素
    // return words.reduce((prev, curr) => curr.match(RegExp(`[${prev}]{1}`, "g")).join("")).split("")
    function strInter(str1, str2) {
        const dist1 = {}
        const dist2 = {}
        for (let i = 0; i < str1.length; i++) {
            dist1[str1[i]] ? dist1[str1[i]]++ : (dist1[str1[i]] = 1)
        }
        for (let i = 0; i < str2.length; i++) {
            dist2[str2[i]] ? dist2[str2[i]]++ : (dist2[str2[i]] = 1)
        }
        let str = ""
        for (let key in dist1) {
            while (dist1[key] && dist2[key]) {
                str += key
                dist1[key]--
                dist2[key]--
            }
        }
        return str
    }
    return words.reduce((prev, curr) => strInter(prev, curr)).split("")
    // const dist = {}
    // const result = []
    // words.forEach((str) => {
    //     const temp = {}
    //     for (let i = 0; i < str.length; i++) temp[str[i]] = true
    //     for (let key in temp) dist[key] ? dist[key]++ : (dist[key] = 1)
    // })
    // for (let key in dist) dist[key] == words.length ? result.push(key) : null
    // return result
}
// debugger
// console.log(commonChars(["cool", "lock", "cook"]))
// @lc code=end
